﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

using UCore;

namespace Twin {
    public partial class frmRdIns : Form {


        public string GeneratedString { get; private set; }
        private string[] arg;
        //private string args;

        private int INST_BITS = 0;
        private int INST_OP = 1;
        private int INST_CMFG = 2;
        private int INST_INSTANT = 3;

        private XPort xport = new XPort();

        public frmRdIns(XPort xport, string content) {           //OP_RD_INS, [cmfg], [instant_fmt]
            InitializeComponent();

            GeneratedString = content;
            this.xport = xport;

            //dgvEdit
            dgvInstant.ColumnHeadersVisible = false;
            dgvInstant.AllowUserToAddRows = false;
            dgvInstant.MouseClick += dgvInstant_MouseClick;     // 为DataGridView的MouseClick事件添加事件处理器
            

            arg = content.Split(',');
            
            
            arg[INST_CMFG] = UI.init_cmbCmfg(cmbCmfg, arg[INST_CMFG]);
            //UI.init_cmbCom(cmbCom, Ini.defaultPort);

            
            string sInstant = Common.RemoveBracketedContent(arg[INST_INSTANT]);
            //if (sInstant.Equals("")) return;
            arg[INST_INSTANT] = sInstant;

            //listEls
            listEls.MouseClick += listEls_MouseClick;   // 绑定新事件
            UI.init_listEls(listEls);
            listEls.ClearSelected();

            UI.init_dgvInstant(dgvInstant, arg[INST_INSTANT]);

            //inst[INST_AREA_SN] = (Twin.TConsole.SnFile++).ToString("x");
        }


        private void frmRdInstant_Load(object sender, EventArgs e) {
            this.TopMost = true;
            this.FormBorderStyle = FormBorderStyle.FixedSingle; // 设置窗体边框样式为固定单线框
            this.MaximizeBox = false;   // 移除最大化按钮
            this.MinimizeBox = false;   // 禁止调整大小

            TConsole.PositionFormAtTopRight(this);
        }


        //删除
        private void dgvInstant_MouseClick(object sender, MouseEventArgs e) {
            if (e.Button == MouseButtons.Right) {       // 检查是否是鼠标右键点击
                if (dgvInstant.CurrentRow != null) {    // 检查是否有当前行
                    // 显示确认消息框
                    DialogResult result = MessageBox.Show("确定要删除当前行吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    // 如果用户点击了“是”，则删除当前行
                    if (result == DialogResult.Yes) {
                        dgvInstant.Rows.Remove(dgvInstant.CurrentRow);
                    }
                    // 删除当前行
                    //dgvEdit.Rows.Remove(dgvEdit.CurrentRow);
                }
            }
        }
        

        //选择: 加要素
        //private void listEls_SelectedIndexChanged(object sender, EventArgs e) {
        //    if (listEls.SelectedItem != null) {     // 检查是否有选中的项
        //        string selectedText = listEls.SelectedItem.ToString();      // 获取ListBox1中选中的项

        //        // 将选中的项添加到ListBox2的尾部
        //        //dgvEdit.Rows.Add(selectedText);


        //        // 将选中的项添加到DataGridView的尾部
        //        int newRow = dgvInstant.Rows.Add(selectedText);
        //        dgvInstant.Rows[newRow].Cells[1].Value = ((uint)newRow).ToString("X2"); // "X2" 格式化为两位16进制

        //        // 设置新行的第一列为选中状态
        //        dgvInstant.CurrentCell = dgvInstant.Rows[newRow].Cells[0];
        //    }
        //}
        private void listEls_MouseClick(object sender, MouseEventArgs e) {
            int index = listEls.IndexFromPoint(e.Location);
            if (index != ListBox.NoMatches) {
                string selectedText = listEls.Items[index].ToString();
                int newRow = dgvInstant.Rows.Add(selectedText);
                dgvInstant.Rows[newRow].Cells[1].Value = ((uint)newRow).ToString("X2");
                dgvInstant.CurrentCell = dgvInstant.Rows[newRow].Cells[0];
            }
        }


        private void listBox2_SelectedIndexChanged_1(object sender, EventArgs e) {

        }

        private void dgvEdit_CellContentClick(object sender, DataGridViewCellEventArgs e) {

        }


        private void btnGenerate_Click(object sender, EventArgs e) {
            // 遍历DataGridView的所有行
            string s = "";
            foreach (DataGridViewRow row in dgvInstant.Rows) {
                // 检查行是否为新行（即用户可以添加但未提交的行）
                if (!row.IsNewRow) {
                    // 访问第一列的值
                    s += row.Cells[0].Value.ToString();
                    s += ">";
                    //Console.WriteLine(value); // 打印到控制台，或者可以进行其他操作
                }
            }
            //if (!s.Equals("")) {
            //    inst[INST_KVS] = s.Substring(0, s.Length - 1);
            //}
            GeneratedString = arg[INST_OP] + "," + arg[INST_CMFG] + "[cmfg]," + arg[INST_INSTANT] + "[instant_fmt]";
            this.Close();
        }

        //private void cmbAreas_SelectedIndexChanged(object sender, EventArgs e) {
        //    inst[INST_I_AREA] = cmbAreas.SelectedIndex.ToString();
        //    init_listSrc(cmbAreas.SelectedIndex);
        //}

        private void cmbCmfg_SelectedIndexChanged(object sender, EventArgs e) {
            arg[INST_CMFG] = cmbCmfg.SelectedIndex.ToString();
            if (arg[INST_CMFG].Equals("空")) {
                arg[INST_CMFG] = "";
            }
        }

        private void cmbCmfg_SelectedIndexChanged_1(object sender, EventArgs e) {
            arg[INST_CMFG] = cmbCmfg.SelectedItem.ToString();
            if (arg[INST_CMFG].Equals("空")) {
                arg[INST_CMFG] = "";
            }
        }

        private void dgvInstant_CellContentClick(object sender, DataGridViewCellEventArgs e) {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {

        }


        private string jointCxs(DataGridView dgvInstant) {
            if (dgvInstant == null || dgvInstant.Columns.Count < 2)
                return string.Empty;

            StringBuilder sb = new StringBuilder();
            foreach (DataGridViewRow row in dgvInstant.Rows) {
                if (!row.IsNewRow) {
                    var cell = row.Cells[1];
                    sb.Append(cell.Value?.ToString() ?? "");
                }
            }
            return sb.ToString();
        }


        private void btnSend_Click(object sender, EventArgs e) {
            CInfo cInfo = new CInfo();

            Msg.setInfo_bits(ref cInfo, arg[INST_BITS]);

            arg[INST_INSTANT] = jointCxs(dgvInstant);

            cInfo.sOpArgs = arg[INST_OP] + "," + arg[INST_CMFG] + "," + arg[INST_INSTANT];
            string wr_kvs = "";

            TConsole.sendAsProtocol(xport, ref cInfo, wr_kvs, "cobra");
        }
    }
}

